from random import choice
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.shared import Cm
from openpyxl import load_workbook
from docx.shared import Pt
from docx.oxml.ns import qn

def xlsx2docx1(fn):
    wb = load_workbook(fn,data_only=True)
    document = Document()
    document.styles['Normal'].font.name = u'宋体'
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    document.styles['Normal'].font.size = Pt(12)
    document.add_paragraph('    地块{0}由点号J1-J{1},J1围成')
    document.add_paragraph('    占地面积：P={:.2f}平方米，合{}亩。')
    table_styles = ['Table Grid']




    for ws in wb.worksheets:
        section = document.sections[0]
        section.page_width = Cm(21)  # 设置A4纸的宽度
        section.page_height = Cm(29.7)  # 设置A4纸的高度
        # 创建表头
        rows = list(ws.rows)
        #document.add_paragraph('地块'+ws.title[5]+'由点号')
        document.add_paragraph('')
        document.add_paragraph('    地块{0}由点号J1-J{1},J1围成'.format(ws.title[5],len(rows)-1))
        document.add_paragraph('    占地面积：P={:.2f}平方米，合{}亩。'.format(float(ws.cell(2,4).value),ws.cell(2,5).value))
        table = document.add_table(rows=len(rows),
                                   cols=len(rows[0])-2,
                                   style=choice(table_styles))

        for table_col in range(1,4):
            table.cell(0,table_col-1).text = str(ws.cell(1,table_col).value)
        for table_row in range(2,len(rows)+1):
            for table_col in range(2,4):
                table.cell(table_row-1,table_col-1).text = format(ws.cell(table_row,table_col).value, '.3f')
        for table_row in range(2, len(rows) + 1):
            table.cell(table_row - 1, 0).text = str(ws.cell(table_row,1).value)
        for table_row in range(0,len(rows)):
            for table_col in range(0,3):
                # 垂直居中
                table.cell(table_row,table_col).paragraphs[0].alignment = WD_TABLE_ALIGNMENT.CENTER
                table.cell(table_row,table_col).vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
        for row in table.rows:
                # 设置行高
                row.height = Cm(1)


    document.save('report.docx')
xlsx2docx1('test.xlsx')

